package com.example;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.example.vo.CommandLineArgs;

public class NexusBackupApp {

    private static final String DEFAULT_LOCAL_PATH = "./downloaded_jars";

    public static void main(String[] args) {
        try {
            // 解析命令行参数
            CommandLineArgs cmdArgs = HttpUtils.parseCommandLineArgs(args);

            // 检查必要参数
            HttpUtils.checkRequiredParams(cmdArgs);

            // 创建本地保存目录
            createLocalDirectory(cmdArgs.getLocalPath());

            // 获取仓库中的所有文件列表
            String artifactsListFile = fetchArtifactsList(cmdArgs);

            // 下载所有文件并保留目录结构
            downloadArtifacts(cmdArgs, artifactsListFile);

            System.out.println("[INFO] 所有操作已完成。");

        } catch (Exception e) {
            System.err.println("[ERROR] " + e.getMessage());
            e.printStackTrace();
            HttpUtils.showHelp();
            System.exit(1);
        }
    }

    private static void createLocalDirectory(String localPath) {
        File dir = new File(localPath);
        if (!dir.exists()) {
            System.out.println("[INFO] 创建本地保存目录: " + localPath);
            boolean created = dir.mkdirs();
            if (!created) {
                throw new RuntimeException("创建目录失败: " + localPath);
            }
        }
    }

    private static String fetchArtifactsList(CommandLineArgs cmdArgs) throws Exception {
        // 不限制格式，获取仓库中的所有文件
        String nexusApiUrl = cmdArgs.getNexusUrl() + (cmdArgs.getNexusUrl().endsWith("/") ? "" : "/") + 
                            "service/rest/v1/search/assets?repository=" + cmdArgs.getRepositoryName();// + "&sort=name";
        String tempFile = cmdArgs.getLocalPath() + File.separator + "artifacts_list.json";
        File tempFileObj = new File(tempFile);

        // 检查artifacts_list.json文件是否已经存在且有效
        if (tempFileObj.exists() && tempFileObj.length() > 0) {
            System.out.println("[INFO] artifacts_list.json 文件已存在，直接使用现有文件...");
            
            // 验证文件是否有效
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(new File(tempFile).toURI().toURL().openStream()))) {
                StringBuilder jsonBuilder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    jsonBuilder.append(line);
                }
                JSONObject jsonObject = JSON.parseObject(jsonBuilder.toString());
                if (jsonObject.containsKey("items") && jsonObject.get("items") instanceof JSONArray) {
                    return tempFile;
                }
                System.out.println("[INFO] 现有 artifacts_list.json 文件无效，重新下载...");
            } catch (Exception e) {
                System.out.println("[INFO] 读取现有 artifacts_list.json 文件失败，重新下载: " + e.getMessage());
            }
        }

        System.out.println("[INFO] 正在获取仓库 " + cmdArgs.getRepositoryName() + " 中的所有文件列表...");
        System.out.println("[INFO] 这个过程可能需要一些时间，请耐心等待...");

        // 使用HttpUtils发送HTTP请求获取文件列表
        try {
            String response = HttpUtils.sendGetRequest(nexusApiUrl, cmdArgs.getUsername(), cmdArgs.getPassword(),
                                                      cmdArgs.getProxyHost(), cmdArgs.getProxyPort(), cmdArgs.getProxyUsername(), cmdArgs.getProxyPassword());
            
            // 保存响应到临时文件
            try (FileOutputStream outputStream = new FileOutputStream(tempFile)) {
                outputStream.write(response.getBytes());
                outputStream.write('\n');
            }
        } catch (Exception e) {
            if (e.getMessage().contains("HTTP请求失败")) {
                throw new RuntimeException("获取文件列表失败: " + e.getMessage() + ", 请检查Nexus地址、用户名、密码和仓库名称是否正确。");
            }
            throw e;
        }

        // 解析JSON检查是否有文件
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new File(tempFile).toURI().toURL().openStream()))) {
            StringBuilder jsonBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                jsonBuilder.append(line);
            }
            JSONObject jsonObject = JSON.parseObject(jsonBuilder.toString());
            JSONArray items = jsonObject.getJSONArray("items");
            
            // 统计需要下载的jar和pom文件数量
            int artifactsCount = 0;
            for (int i = 0; i < items.size(); i++) {
                JSONObject item = items.getJSONObject(i);
                String path = item.getString("path");
                if (!path.endsWith(".tar.gz")) {
                    artifactsCount++;
                }
            }

            if (artifactsCount == 0) {
                System.out.println("[INFO] 在仓库 " + cmdArgs.getRepositoryName() + " 中未找到jar和pom文件。");
                System.exit(0);
            }

            System.out.println("[INFO] 找到 " + artifactsCount + " 个jar和pom文件需要下载。");
        }

        return tempFile;
    }

    private static void downloadArtifacts(CommandLineArgs cmdArgs, String artifactsListFile) throws Exception {
        int totalDownloaded = 0;
        int totalFailed = 0;

        System.out.println("[INFO] 开始下载所有文件到 " + cmdArgs.getLocalPath() + "，并保留原始目录结构...");

        // 解析JSON文件获取所有downloadUrl
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new File(artifactsListFile).toURI().toURL().openStream()))) {
            StringBuilder jsonBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                jsonBuilder.append(line);
            }
            JSONObject jsonObject = JSON.parseObject(jsonBuilder.toString());
            JSONArray items = jsonObject.getJSONArray("items");

            for (int i = 0; i < items.size(); i++) {
                JSONObject item = items.getJSONObject(i);
                String downloadUrl = item.getString("downloadUrl");
                String path = item.getString("path");

                // 只下载jar和pom文件
                if (!path.endsWith(".jar") && !path.endsWith(".pom")) {
                    continue;
                }

                // 构建本地保存路径（保留目录结构）
                String localFilePath = cmdArgs.getLocalPath() + File.separator + path;
                File localFile = new File(localFilePath);
                File localDir = localFile.getParentFile();

                // 创建必要的目录结构
                if (!localDir.exists()) {
                    localDir.mkdirs();
                }

                System.out.println("[INFO] 正在下载: " + path);

                try {
                    // 使用HttpUtils下载文件
                    HttpUtils.downloadFile(downloadUrl, localFilePath, cmdArgs.getUsername(), cmdArgs.getPassword(),
                                          cmdArgs.getProxyHost(), cmdArgs.getProxyPort(), cmdArgs.getProxyUsername(), cmdArgs.getProxyPassword());
                    totalDownloaded++;
                    System.out.println("[INFO] 下载成功: " + path);
                } catch (Exception e) {
                    totalFailed++;
                    System.err.println("[ERROR] 下载失败: " + path + ", 错误: " + e.getMessage());
                }
            }
        }

        System.out.println("[INFO] 下载完成。成功: " + totalDownloaded + ", 失败: " + totalFailed);

        // 清理临时文件
        // new File(artifactsListFile).delete();
    }


}